package library

import (
	"blog/models"
)

const SelectTrue = 1

type PageTitle struct {
	Title string
}

type Menu struct {
	Id     int
	Name   string
	Url    string
	Icon   string
	Select int
	Type   int
	Child  []Menu
}

func MenuHtml(url string) string {
	var html = ""
	menuList := MenuTree(url, -3)
	for _, v := range menuList {
		html += buildMenuHtml(v)
	}
	return html
}

func buildMenuHtml(menu Menu) string {
	var html = ""
	if menu.Type == 3 {
		return ""
	}
	if menu.Type == 1 { //分类标签
		html += "<li class=\"nav-header\">" + menu.Name + "</li>"
		for _, cv := range menu.Child {
			html += buildMenuHtml(cv)
		}
		return html
	}
	if len(menu.Child) > 0 && menu.Type == 2 { //多级菜单
		var menuOpen = ""
		var active = ""
		var childHtml = ""
		if menu.Select == 1 {
			menuOpen = "menu-open"
			active = "active"
		}
		for _, cv := range menu.Child {

			childHtml += buildMenuHtml(cv)
		}
		html += `<li class="nav-item has-treeview ` + menuOpen + `">`
		html += `<a href="#" class="nav-link ` + active + `">`
		html += `<i class="nav-icon fa ` + menu.Icon + `"></i>`
		html += `<p>`
		html += menu.Name
		html += `<i class="fa fa-angle-left right"></i>`
		html += `</p>`
		html += `</a>`
		html += `<ul class="nav nav-treeview">`
		html += childHtml
		html += `</ul>`
		html += `</li>`
	} else if len(menu.Child) == 0 { //单独菜单
		html += buildOnlyMenu(menu)
	}
	return html
}

func buildOnlyMenu(menu Menu) string {
	var (
		html   = ""
		active = ""
	)
	if menu.Select == 1 {
		active = "active"
	}
	html += `<li class="nav-item">`
	html += `<a href="` + menu.Url + `" class="nav-link ` + active + `">`
	html += `<i class="nav-icon fas fa ` + menu.Icon + `"></i>`
	html += `<p>`
	html += menu.Name
	html += `</p>`
	html += `</a>`
	html += `</li>`
	return html
}

func MenuTree(url string, all ...int) []Menu {
	var menuModel = models.NewMenu()
	menu := make([]Menu, 0)
	if len(all) > 0 {
		menuModel.Type = -3
	}
	menuModel.IsShow = 1
	menuAllList, total, err := menuModel.MenuList()
	if err != nil || total == 0 {
		return menu
	}
	menu, _ = dealMenu(menuAllList, url, 0)
	return menu
}

func dealMenu(menuList []models.Menu, url string, pid int) ([]Menu, int) {
	if url == "/" { //首页链接 / 或 /admin/welcome
		url = "/admin/welcome"
	}
	var (
		menuArray   []Menu
		menuSelect  = 0
		childSelect = 0
	)
	for _, v := range menuList {
		var menu Menu
		if v.Pid == pid {
			menu.Id = v.Id
			menu.Url = v.MenuUrl
			menu.Name = v.MenuName
			menu.Icon = v.Icon
			menu.Type = v.Type
			menu.Child, childSelect = dealMenu(menuList, url, v.Id)
			if v.MenuUrl == url || childSelect == SelectTrue {
				menu.Select = SelectTrue
				menuSelect = SelectTrue
			}
			menuArray = append(menuArray, menu)
		}
	}
	return menuArray, menuSelect
}
